import { Component, OnInit } from '@angular/core';

import {Observable, Subject} from "rxjs";

import {debounceTime,distinctUntilChanged, switchMap} from "rxjs/operators";

import {HeroObject} from "../model/heroObject";

import {HomeService} from "../home/home.service";

@Component({
  selector: 'app-hero-search',
  templateUrl: './hero-search.component.html',
  styleUrls: ['./hero-search.component.css']
})
export class HeroSearchComponent implements OnInit {

  heros$ : Observable<HeroObject[]>;

  private searchTerms = new Subject<string>();

  constructor( private homeService : HomeService) {

  }

  ngOnInit() {
      this.fetchSerachResult();
  }


   //搜索事件
   searchEvent(name : string) : void{
     this.searchTerms.next(name);
   }

   //获取搜索的结果
    fetchSerachResult():void{
      this.heros$ = this.searchTerms.pipe(
        //延时300ms
        debounceTime(300),

        //停止
        distinctUntilChanged(),

        switchMap((term : string) =>this.homeService.searchHeroEvent(term)),
      );
    }
}
